package com.tanguy.user.ui.trip.activity.choice

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.provider.ContactsContract
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import cn.sinata.xldutils_kotlin.adapter.BaseRecyclerAdapter
import cn.sinata.xldutils_kotlin.adapter.HFRecyclerAdapter
import cn.sinata.xldutils_kotlin.adapter.util.ViewHolder
import cn.sinata.xldutils_kotlin.utils.SPUtils
import com.mdchuxing.user.database.ContactHistoryManager
import com.tanguy.user.Const
import com.tanguy.user.R
import com.tanguy.user.base.ImmersionTitleActivity
import com.tanguy.user.bean.PeopleModel
import com.tanguy.user.utlis.extend.checkPhoneNumber
import com.tanguy.user.utlis.extend.click
import com.tanguy.user.utlis.extend.getEditTextString
import com.tanguy.user.utlis.extend.rxPermissionsContacts
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration
import kotlinx.android.synthetic.main.activity_help_other_call.*
import org.jetbrains.anko.toast
import java.util.regex.Pattern


/**
 * 替他人叫车
 */
class HelpOtherCallActivity : ImmersionTitleActivity() {

    override fun setContentViewRes(): Int=R.layout.activity_help_other_call
    var mData = ArrayList<PeopleModel>()
    var peopleAdapter: PeopleAdapter = PeopleAdapter(mData)

    override fun initView() {
        super.initView()
        title = "替他人叫车"
        titleBar.addRightButton("确定", 0, View.OnClickListener {
            val name = getEditTextString(tv_people_name)
            if (TextUtils.isEmpty(name)) {
                toast("姓名不能为空")
                return@OnClickListener
            }
            val phone = getEditTextString(tv_phone)
            if (!checkPhoneNumber(phone))return@OnClickListener

            if (!ContactHistoryManager.isHasSameData(this, phone)) {
                ContactHistoryManager.saveContact(this, name, phone)
            }
            val me=name=="自己乘车"&&phone==SPUtils.instance().getString(Const.User.PHONE)
            setData(name, phone,me)
        })

    }
    override fun initEvent() {
        super.initEvent()
        click(tv_clear) {
            //清空表
            ContactHistoryManager.clearTable(this@HelpOtherCallActivity)
            mData.clear()
            //添加自己的信息
            val phone = SPUtils.instance().getString(Const.User.PHONE)
            ContactHistoryManager.saveContact(this@HelpOtherCallActivity, "自己乘车", phone)
            val peoples = ContactHistoryManager.getPeoples(this@HelpOtherCallActivity)
            mData.addAll(peoples)
            peopleAdapter.notifyDataSetChanged()
        }
        click(tv_contact) {
            rxPermissionsContacts{
                val intent = Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI)
                startActivityForResult(intent, 0)
            }

        }

    }

    private fun setData(name: String, phone: String,isMe:Boolean=false) {
        val intent = Intent()
        intent.putExtra("name", name)
        intent.putExtra("me", isMe)
        intent.putExtra("phone", phone)
        setResult(Activity.RESULT_OK, intent)
        finish()
    }

    override fun initData() {
        super.initData()
        val defaultItemDecoration = HorizontalDividerItemDecoration.Builder(this)
                .colorResId(R.color.dividing_line_color)
                .marginResId(R.dimen.activity_horizontal_margin, R.dimen.activity_horizontal_margin)
                .size(1)
                .build()
        rv_history.apply {
            layoutManager=LinearLayoutManager(this@HelpOtherCallActivity)
            addItemDecoration(defaultItemDecoration)
            adapter = peopleAdapter
        }

        peopleAdapter.setOnItemClickListener(object : BaseRecyclerAdapter.OnItemClickListener {
            override fun onItemClick(view: View?, position: Int) {
                val model = mData[position]
                setData(model.name, model.phone,position==mData.size-1)
            }
        })
        val phone = SPUtils.instance().getString(Const.User.PHONE)
        if (!ContactHistoryManager.isHasSameData(this,phone)){
            ContactHistoryManager.saveContact(this@HelpOtherCallActivity, "自己乘车", phone)
        }

        val peoples = ContactHistoryManager.getPeoples(this)
        mData.addAll(peoples)
        peopleAdapter.notifyDataSetChanged()
    }



    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 0 && data != null) {
                val uri = data.data
                val s = getPhoneContacts(uri)
                if (s != null) {
                    tv_people_name.setText(s[0])
                    tv_phone.setText(filterUnNumber(s[1]))
                }
            }
        }
    }

    private fun getPhoneContacts(uri: Uri): ArrayList<String>? {
//        val contact = arrayOfNulls<String>(2)
        val contact = arrayListOf<String>()
        //得到ContentResolver对象
        val cr = contentResolver
        //取得电话本中开始一项的光标
        val cursor = cr.query(uri, null, null, null, null)
        if (cursor != null) {
            cursor.moveToFirst()
            //取得联系人姓名
            val nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)
            contact.add(cursor.getString(nameFieldColumnIndex))
            //取得电话号码
            val ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID))
            val phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null)
            if (phone != null) {
                while (phone.moveToNext()) {
                    contact.add(phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)))

                }
                phone.close()
            }
            cursor.close()
        } else {
            return null
        }
        return contact
    }


    /**
     * 替他人叫车 历史记录adapter
     * Created by zhangyujiu on 2017/8/9.
     */
    class PeopleAdapter(mData: ArrayList<PeopleModel>) : HFRecyclerAdapter<PeopleModel>(mData, R.layout.item_people) {
        override fun onBind(holder: ViewHolder, position: Int, data: PeopleModel) {
            holder.setText(R.id.tv_name_phone, "${data.name} (${data.phone})")
        }
    }

    /**
     * 删除号码中的所有非数字
     *
     * @param str
     * @return
     */
    fun filterUnNumber(str: String?): String? {
        var str: String? = str ?: return null
        if (str!!.startsWith("+86")) {
            str = str.substring(3, str.length)
        }
        //		if (str.contains("#")) {
        //
        //			return str.replaceAll("#", "@");
        //		}

        // 只允数字
        val regEx = "[^0-9]"
        val p = Pattern.compile(regEx)
        val m = p.matcher(str)
        // 替换与模式匹配的所有字符（即非数字的字符将被""替换）
        // 对voip造成的负数号码，做处理
        return if (str.startsWith("-")) {
            "-" + m.replaceAll("").trim { it <= ' ' }
        } else {
            m.replaceAll("").trim { it <= ' ' }
        }

    }
}
